package controllers

import (
	"LoveU/models"
	"LoveU/utils"
	"fmt"
	"io"
	"math/rand"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
)

// 方法描述：上传用户的头像并修改名字
// 功能一：
// 检查上传文件的类型
// 仅支持png和jeg两种图片
// utils.UNKNOWN_ERROR：系统错误
// utils.ALBUM_DELETE_FAILED：删除文件出错
// utils.ALBUM_RENAME_FAILED：删除文件失败
// utils.ALBUM_UPLOAD_JPEG：jpeg
// utils.ALBUM_UPLOAD_GIF：png
// utils.ALBUM_UPLOAD_PNG：gif
// utils.ALBUM_UPLOAD_FORMAT_DENIED：不兼容的图片类型
func picType(path, parentpath string, userid int64) int64 {

	userPic := parentpath + strconv.FormatInt(userid, 10)

	// 判断文件是否存在
	_, err := os.Stat(userPic + ".png")
	if err == nil {
		os.Remove(userPic + ".png")
	}
	_, err = os.Stat(userPic + ".jpg")
	if err == nil {
		os.Remove(userPic + ".jpg")
	}
	_, err = os.Stat(userPic + ".gif")
	if err == nil {
		os.Remove(userPic + ".gif")
	}

	pic, err := os.Open(path)
	defer pic.Close()
	if err != nil {
		beego.Error(err.Error())
		return utils.UNKNOWN_ERROR
	}
	buff := make([]byte, 512)
	_, err = pic.Read(buff)
	if err != nil {
		beego.Error(err.Error())
		return utils.UNKNOWN_ERROR
	}

	fileType := http.DetectContentType(buff)
	pic.Close()

	switch fileType {
	case "image/jpeg", "image/jpg":
		err = os.Rename(path, userPic+".jpg")
		if err != nil {
			return utils.ALBUM_RENAME_FAILED
		}
		return utils.ALBUM_UPLOAD_JPEG
	case "image/gif":
		err = os.Rename(path, userPic+".gif")
		if err != nil {
			return utils.ALBUM_RENAME_FAILED
		}
		return utils.ALBUM_UPLOAD_GIF
	case "image/png":
		err = os.Rename(path, userPic+".png")
		if err != nil {
			return utils.ALBUM_RENAME_FAILED
		}
		return utils.ALBUM_UPLOAD_PNG
	default:
		err := os.Remove(path)
		if err != nil {
			//删除文件失败
			return utils.ALBUM_DELETE_FAILED
		}
		return utils.ALBUM_UPLOAD_FORMAT_DENIED
	}

}

const ALUMB = "alumb/"

// 功能二：用户相册
// 每个用户系统都会为他们新建一个新的目录
func createAlumb(userid int64) int64 {
	userid_str := strconv.FormatInt(userid, 10)
	_, err := os.Stat(userid_str)
	if os.IsNotExist(err) {
		err = os.Mkdir(ALUMB+userid_str, os.ModePerm)
		if err != nil {
			return utils.ALBUM_DIR_CREATE_OK
		}
		return utils.ALBUM_DELETE_FAILED
	}

	return utils.ALBUM_FILE_EXISTS
}

//创建临时目录
func createDir(path string) int64 {
	_, err := os.Stat(path)
	if err != nil {
		err = os.Mkdir(path, os.ModePerm)
		if err != nil {
			return utils.ALBUM_DIR_CREATE_OK
		}
		return utils.ALBUM_DELETE_FAILED
	}
	return utils.ALBUM_FILE_EXISTS
}

// 功能一：
// 检查上传文件的类型
// 仅支持png和jeg两种图片
// utils.UNKNOWN_ERROR：系统错误
// utils.ALBUM_DELETE_FAILED：删除文件出错
// utils.ALBUM_RENAME_FAILED：删除文件失败

// utils.ALBUM_UPLOAD_JPEG：jpeg
// utils.ALBUM_UPLOAD_GIF：png
// utils.ALBUM_UPLOAD_PNG：gif
// utils.ALBUM_UPLOAD_FORMAT_DENIED：不兼容的图片类型
func picTypeAlumb(path, parentpath string, userid int64) int64 {
	pic, err := os.Open(path)
	defer pic.Close()
	if err != nil {
		return utils.UNKNOWN_ERROR
	}
	buff := make([]byte, 512)
	_, err = pic.Read(buff)
	if err != nil {
		return utils.UNKNOWN_ERROR
	}

	fileType := http.DetectContentType(buff)
	pic.Close()

	//获取系统时间并改名
	sysTime := time.Now().String()
	sysTime = strings.Replace(sysTime, ":", " ", -1)
	sysTime = strings.Replace(sysTime, " ", "-", -1)

	picPath := parentpath + strconv.FormatInt(userid, 10) + "/" + sysTime

	switch fileType {
	case "image/jpeg", "image/jpg":
		models.WriteToAlumbDB(userid, sysTime+".jpg")
		err = os.Rename(path, picPath+".jpg")
		if err != nil {
			return utils.ALBUM_RENAME_FAILED
		}
		return utils.ALBUM_UPLOAD_JPEG
	case "image/gif":
		models.WriteToAlumbDB(userid, sysTime+".gif")
		err = os.Rename(path, picPath+".gif")
		if err != nil {
			return utils.ALBUM_RENAME_FAILED
		}
		return utils.ALBUM_UPLOAD_GIF
	case "image/png":
		models.WriteToAlumbDB(userid, sysTime+".png")
		err = os.Rename(path, picPath+".png")
		if err != nil {
			return utils.ALBUM_RENAME_FAILED
		}
		return utils.ALBUM_UPLOAD_PNG
	default:
		err := os.Remove(path)
		if err != nil {
			//删除文件失败
			return utils.ALBUM_DELETE_FAILED
		}
		return utils.ALBUM_UPLOAD_FORMAT_DENIED
	}

}

// 管理员上传图片
func picTypeAll(path, parentpath string) (int64, string) {
	pic, err := os.Open(path)
	defer pic.Close()
	if err != nil {
		return utils.UNKNOWN_ERROR, ""
	}
	buff := make([]byte, 512)
	_, err = pic.Read(buff)
	if err != nil {
		return utils.UNKNOWN_ERROR, ""
	}

	fileType := http.DetectContentType(buff)
	pic.Close()

	//获取系统时间并改名
	sysTime := time.Now().String()
	sysTime = strings.Replace(sysTime, ":", " ", -1)
	sysTime = strings.Replace(sysTime, " ", "-", -1) + GetRandomString(20)

	//重命名后的名字
	picPath := parentpath + sysTime

	switch fileType {
	case "image/jpeg", "image/jpg":
		err = os.Rename(path, picPath+".jpg")
		if err != nil {
			return utils.ALBUM_RENAME_FAILED, ""
		}
		return utils.ALBUM_UPLOAD_JPEG, sysTime + ".jpg"
	case "image/gif":
		err = os.Rename(path, picPath+".gif")
		if err != nil {
			return utils.ALBUM_RENAME_FAILED, ""
		}
		return utils.ALBUM_UPLOAD_GIF, sysTime + ".gif"
	case "image/png":
		err = os.Rename(path, picPath+".png")
		if err != nil {
			return utils.ALBUM_RENAME_FAILED, ""
		}
		return utils.ALBUM_UPLOAD_PNG, sysTime + ".png"
	default:
		err := os.Remove(path)
		if err != nil {
			//删除文件失败
			return utils.ALBUM_DELETE_FAILED, ""
		}
		return utils.ALBUM_UPLOAD_FORMAT_DENIED, ""
	}

}

// 用户上传心情图片
func picTypeUser(path, parentpath string) (int64, string) {
	pic, err := os.Open(path)
	defer pic.Close()
	if err != nil {
		return utils.UNKNOWN_ERROR, ""
	}
	buff := make([]byte, 512)
	_, err = pic.Read(buff)
	if err != nil {
		return utils.UNKNOWN_ERROR, ""
	}

	fileType := http.DetectContentType(buff)
	pic.Close()

	//获取系统时间并改名
	sysTime := time.Now().String()
	sysTime = strings.Replace(sysTime, " ", "-", -1) + GetRandomString(20)

	//重命名后的名字
	picPath := parentpath + sysTime

	switch fileType {
	case "image/jpeg", "image/jpg":
		err = os.Rename(path, picPath+".jpg")
		if err != nil {
			return utils.ALBUM_RENAME_FAILED, ""
		}
		return utils.ALBUM_UPLOAD_JPEG, sysTime + ".jpg"
	case "image/gif":
		err = os.Rename(path, picPath+".gif")
		if err != nil {
			return utils.ALBUM_RENAME_FAILED, ""
		}
		return utils.ALBUM_UPLOAD_GIF, sysTime + ".gif"
	case "image/png":
		err = os.Rename(path, picPath+".png")
		if err != nil {
			return utils.ALBUM_RENAME_FAILED, ""
		}
		return utils.ALBUM_UPLOAD_PNG, sysTime + ".png"
	default:
		err := os.Remove(path)
		if err != nil {
			//删除文件失败
			return utils.ALBUM_DELETE_FAILED, ""
		}
		return utils.ALBUM_UPLOAD_FORMAT_DENIED, ""
	}

}

// 文件复制
// src：原文件
// dst：目标文件
func CopyFile(src, dst string) (w int64, err error) {
	srcFile, err := os.Open(src)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer srcFile.Close()

	dstFile, err := os.Create(dst)

	if err != nil {
		fmt.Println(err.Error())
		return
	}

	defer dstFile.Close()

	return io.Copy(dstFile, srcFile)
}

// //生成随机字符串
// func GetRandomString(len int64) string {
// 	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// 	bytes := []byte(str)
// 	result := []byte{}
// 	r := rand.New(rand.NewSource(time.Now().UnixNano()))
// 	strLen := len([]rune(str))
// 	for i := 0; i < len(str); i++ {
// 		result = append(result, bytes[8])
// 	}
// 	return string(result)
// }

/**
*生成随机字符
**/
func GetRandomString(length int) string {
	rand.Seed(time.Now().UnixNano())
	rs := make([]string, length)
	for start := 0; start < length; start++ {
		t := rand.Intn(3)
		if t == 0 {
			rs = append(rs, strconv.Itoa(rand.Intn(10)))
		} else if t == 1 {
			rs = append(rs, string(rand.Intn(26)+65))
		} else {
			rs = append(rs, string(rand.Intn(26)+97))
		}
	}
	return strings.Join(rs, "")
}
